//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { observer } from 'mobx-react';
import { Form, Input, Modal, message } from "antd";
import { useStores } from "@/hooks";
import { get_global_server_addr, get_vendor_config, set_global_server_addr } from "@/api/client_cfg";
import { useTranslation } from "react-i18next";

const GlobalServerModal = () => {
    const { t } = useTranslation();

    const appStore = useStores('appStore');
    const [serverAddr, setServerAddr] = useState("");
    const [defaultAddr, setDefaultAddr] = useState("");

    const loadServerAddr = async () => {
        const res = await get_global_server_addr();
        setServerAddr(res.replaceAll("http://", ""));
    };

    const saveServerAddr = async () => {
        await set_global_server_addr(serverAddr.replaceAll("http://", ""));
        appStore.showGlobalServerModal = false;
        message.info(t("text.setSuccess"));
    };

    const loadDefaultAddr = async () => {
        const cfg = await get_vendor_config();
        setDefaultAddr(cfg.default_server_addr);
    };

    useEffect(() => {
        loadServerAddr();
        loadDefaultAddr();
    }, []);

    return (
        <Modal open title={t("header.setupGolbalServer")} mask={false}
            okText={t("text.set")} okButtonProps={{ disabled: serverAddr == "" }}
            onCancel={e => {
                e.stopPropagation();
                e.preventDefault();
                appStore.showGlobalServerModal = false;
            }}
            onOk={e => {
                e.stopPropagation();
                e.preventDefault();
                saveServerAddr();
            }}>
            <Form>
                <Form.Item label={t("text.serverAddr")} help={
                    <div>
                        <p>{t("header.defaultOfficalServer")}:{defaultAddr},{t("header.changePrivServer")}</p>
                        <p>{t("header.globalServerAffect")}</p>
                    </div>
                }>
                    <Input value={serverAddr} onChange={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setServerAddr(e.target.value.trim());
                    }} />
                </Form.Item>
            </Form>
        </Modal>
    );
};

export default observer(GlobalServerModal);